// 是否延迟加载
var lazyOptional = false;

// Datagrid URL参数
var datagrid_url_info = appPath+'/cms/staticManage_listOptionalInfo.do';
var datagrid_url_info_mgr = appPath+'/cms/staticManage_listCascadeInfo.do';

/**
 * 待选资讯控件初始化方法
 */
function initInfoPlugin() {
	$("#sm_optionalGrid").datagrid({
		url: lazyOptional? '' : datagrid_url_info,			
		striped: true,
		remoteSort:false,
		queryParams: getInfoQueryParam(),
		idField:'informationId',
		checkbox:true,
		frozenColumns:[[
		      {field:'ck',checkbox:true}		      
		]],
		columns:[[
		      {field:'title',title:'标题',width:340,align:'left'},
		      {field:'categoryName',title:'所属分类',width:178,align:'left'},
		      {field:'infoSource',title:'来源',width:50,align:'center',
		    	  formatter:function(value,rowData){
		    		  return iSource[value];		    		  
		    	  }
		      },
		      {field:'createTime',title:'创建时间',width:150,align:'left',sortable:true,
		    	  formatter:function(value,rowData){
		    		  return $.DateUtil.format(new Date(value),'yyyy-MM-dd hh:mm:ss');
		    	  }
		      }		      
		 ]],
		 pagination:true,
		 pageNumber:1,
		 rownumbers:true,
		 toolbar:[{
				id:'btnOptionaladd',
				text:'增加',
				iconCls:'icon-add',
				handler:function(){
					var selections = $("#sm_optionalGrid").datagrid('getSelections');
					if(selections == null || selections == ''){
						$.messager.alert('提示信息','请选择要关联的数据！','info');
						return ;
					}else{
						$("#sm_optionalGrid").datagrid("loading");
						var postData = "[";
						var typeId = $(dialog_id).data("typeId");
						for(var i=0; i<selections.length; i++){
							postData += "{\"typeId\":" + typeId + ", \"informationId\":" + selections[i].informationId + "}";
							postData += (i != selections.length -1? "," : "");
						}
						postData += "]";
						
						$.loading(true);
						$.ajax({
						   type: "post",
						   url: appPath+'/cms/staticManage_saveCascadeInfo.do',
						   data: "&layoutInfo.jsonData= " + postData,
						   success: function(msg){
							   $.loading(false);
							   if (msg == "ok") 
								   doReloadOptional();
								else {
									$("#sm_optionalGrid").datagrid("loaded");
									$.messager.alert('提示信息','资讯关联失败，请稍后重试！','error');									
								}
						   },
						   error: function(XMLHttpRequest, textStatus, errorThrown) {
							   $.loading(false);
							   $("#sm_optionalGrid").datagrid("loaded");
							   $.messager.alert('提示信息','资讯关联失败，请稍后重试！','error');
						   }
						});
					}
				}
			},'-',{
				id:'btnOptionalMgr',
				text:'管理',
				iconCls:'icon-reset',
				handler:function(){
					initInfoManagePlugin();
					initSearchItemForManageInfo();
					showDataWindow("#cascadeDlg", $(dialog_id).data("typeName") + "陈列管理列表");
				}
			}]
	});
	if (lazyOptional)
		$('#sm_optionalGrid').datagrid('options').url = datagrid_url_info;
}

/**
 * 资讯管理控件初始化方法
 */
function initInfoManagePlugin() {
	$("#sm_cascadeGrid").datagrid({
		url: lazyOptional? '' : datagrid_url_info_mgr,			
		striped: true,
		remoteSort:false,
		queryParams: getInfoMgrQueryParam(),
		idField:'informationId',
		checkbox:true,
		frozenColumns:[[
		      {field:'ck',checkbox:true},
		      {field:'informationId',title:'操作',width:40,align:'center',
		    	  formatter:function(value,rowData,rowIndex){
		    	  	  // var dataStr = JSON.stringify(rowData);
		    		  return "<a href='javascript:void(0)'><img border='0' width='12px' height='12px'  src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑' onClick='showLayoutInfoEdit("+rowIndex+")'/></a>";
		    	  }
		      }
		]],
		columns:[[
		      {field:'title',title:'标题',width:200,align:'left'},
		      {field:'categoryName',title:'所属分类',width:118,align:'left'},
		      {field:'infoSource',title:'来源',width:50,align:'center',
					  formatter:function(value,rowData){
						  return iSource[value];		    		  
					  }
			  },
		      {field:'beginTime',title:'发布起始时间',width:130,align:'left',sortable:true,
		    	  formatter:function(value,rowData){
		    		  return $.DateUtil.format(new Date(rowData.layoutInfo.beginTime),'yyyy-MM-dd hh:mm:ss');
		    	  }
		      },
		      {field:'endTime',title:'发布截止时间',width:130,align:'left',sortable:true,
		    	  formatter:function(value,rowData){
		    		  return $.DateUtil.format(new Date(rowData.layoutInfo.endTime),'yyyy-MM-dd hh:mm:ss');
		    	  }
		      },
		      {field:'sortNo',title:'排序',width:49,align:'center',sortable:true,
		    	  formatter:function(value,rowData){
		    		  return rowData.layoutInfo.sortNo;
		    	  }
		      }
		 ]],
		 pagination:true,
		 pageNumber:1,
		 rownumbers:true,
		 toolbar:[{
				id:'btndelMuLayoutInfo',
				text:'删除',
				iconCls:'icon-cancel',
				handler:function(){
					var selections = $("#sm_cascadeGrid").datagrid('getSelections');
					if(selections == null || selections == ''){
						$.messager.alert('提示信息','请选择要删除的数据','info');
						return ;
					}else{
						$.messager.confirm('提示信息','您确定要删除这些记录？',function(r){
							if(r){
								var ids = '';
								for(var i=0;i<selections.length;i++){
									ids += selections[i].informationId+',';
								}
								ids = ids.substring(0,ids.lastIndexOf(','));
								
								$.loading(true);
								$.ajax({
									url:appPath+'/cms/staticManage_delMultiCascadeInfo.do',
									data:"&multi_id=" + ids + "&layoutInfo.typeId=" + $(dialog_id).data("typeId"),
									success:function(data){
										$.loading(false);
										if(data!='ok'){
											$.messager.alert('提示信息','抱歉，删除未能完成，'+data,'error');
										}else{
											doReloadCascade("delete");
										}
									},
									error:function(XMLHttpRequest, textStatus, errorThrown){
										$.loading(false);
										$.messager.alert('提示信息','抱歉，删除未能完成，'+textStatus,'error');
									}
								});		
							}
						});
					}
				}
			}]
	});
	if (lazyOptional)
		$('#sm_cascadeGrid').datagrid('options').url = datagrid_url_info_mgr;
}

/**
 * 控件展现方法
 */
function showOptionalPlugin() {
	if (lazyOptional) {
		initInfoPlugin();
		lazyOptional = false;
	}		
}

/**
 * 展现资讯陈列编辑页面
 * @param {} rowData
 */
function showLayoutInfoEdit(rowIndex){
	var rowData = $("#sm_cascadeGrid").datagrid("getRows")[rowIndex];
	$('#editLayoutInfoForm').form('clear');
	$('#editLayoutInfoForm').form('load',rowData);
	
	$("#layoutInfo_beginTime").datetimebox("setValue", rowData.layoutInfo.beginTime);
	$("#layoutInfo_endTime").datetimebox("setValue", rowData.layoutInfo.endTime);
	$("#layoutInfo_informationId").val(rowData.informationId);
	$("#layoutInfo_typeId").val(rowData.layoutInfo.typeId);
	
	$("#layoutInfo_title").html(rowData.title);
	$("#layoutInfo_categoryName").html(rowData.categoryName);
	$("#layoutInfo_content").html(rowData.content);
	$("#layoutInfo_remark").html(rowData.remark);
	
	$('#editLayoutDlg').window({
		title:'资讯陈列编辑页面',
		iconCls:'icon-edit',
		height: 445,
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	showRelatedSearchItem('#editLayoutInfoForm');
	$('#editLayoutDlg').window('move',{top:100});
	$('#editLayoutDlg').window('open');
	$('#layoutInfo_sortNo').focus();
	$("#ensureBtn").unbind();
	$("#ensureBtn").bind("click", doPostLayoutInfoData);
	
	$('#layoutInfo_sortNo').val(rowData.layoutInfo.sortNo);
}

/**
 * 提交数据
 */
function doPostLayoutInfoData(){
	if(!$('#editLayoutInfoForm').form('validate')){
		return ;
	}	
	var subData = $('#editLayoutInfoForm');  
    var layoutInfo = subData.serialize();    
	
    $.loading(true);
	$.ajax({
		url:appPath+'/cms/staticManage_updateCascadeInfo.do',
		type:"post",
		data:layoutInfo,
		success:function(data){
			$.loading(false);
			if(data!='ok'){
				$.messager.alert('提示信息','抱歉，更新未能完成！','error');
			}else{
				closeLayoutWindow();
				doReloadCascade("update");
			}
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			$.loading(false);
			$.messager.alert('提示信息','抱歉，更新未能完成，'+textStatus,'error');
		}
	});
}

/**
 * 获取参数列表
 * @return {}
 */
function getInfoQueryParam(categoryId){
	var submitObject = new Object();
	submitObject["info.layoutInfo.typeId"] = $(dialog_id).data("typeId");
	submitObject["info.title"] = $.trim($("#info_title").val());
	if (categoryId != undefined && categoryId != null) {
		if ($("#info_categoryId").combobox("getText").length > 0)
			submitObject["info.categoryId"] = categoryId;
	}
	return submitObject;
}

/**
 * 查询可选数据
 */
function doQueryInfo(){
	showOptionalPlugin();
	$("#sm_optionalGrid").datagrid('unselectAll');
	$("#sm_optionalGrid").datagrid('load',getInfoQueryParam());
}

/**
 * 获取资讯管理参数列表
 * @return {}
 */
function getInfoMgrQueryParam(categoryId){
	var submitObject = new Object();
	submitObject["info.layoutInfo.typeId"] = $(dialog_id).data("typeId");
	submitObject["info.title"] = $.trim($("#infoMgr_title").val());
	if (categoryId != undefined && categoryId != null) {
		if ($("#infoMgr_categoryId").combobox("getText").length > 0)
			submitObject["info.categoryId"] = categoryId;
	}
	return submitObject;
}

/**
 * 查询资讯管理数据
 */
function doQueryInfoMgr(){
	$("#sm_cascadeGrid").datagrid('unselectAll');
	$("#sm_cascadeGrid").datagrid('load',getInfoMgrQueryParam());
}

/**
 * 初始化待选资讯搜索项
 */
function initSearchItemForOptionalInfo() {
	/*
	$.post(appPath+'/cms/staticManage_queryInfoCateList.do', function(data) {
		$('#info_categoryId').combobox({  
			data:data["rows"],  
	        valueField:'categoryId',  
	        textField:'categoryName'  
	    }); 
	});
	*/
	showRelatedSearchItem("#infoTable");
}

/**
 * 初始化管理资讯搜索项
 */
function initSearchItemForManageInfo() {
	/*
	$.post(appPath+'/cms/staticManage_queryInfoCateList.do', function(data) {
		$('#infoMgr_categoryId').combobox({  
			data:data["rows"],  
	        valueField:'categoryId',  
	        textField:'categoryName'  
	    }); 
	});
	*/
	showRelatedSearchItem("#infoMgrTable");
}



